﻿if (typeof Axis == "undefined") Axis = {};
if (typeof Axis.Admin == "undefined") Axis.Admin = {};
Axis.Admin.OptionAnswer = {
    ID: 1,
    IndexRow: 1,
    Init: function () {
    },
    CheckOverlap: function (arr) {
        for (var i = 0; i < arr.length; i++)
            for (j = i + 1; j < arr.length; j++)
                if (arr[i] == arr[j])
                    return arr[i];
        return -9999;
    },
    Update: function (type, opts) {
        var ScaleTextFrom = "";
        var ScaleTextTo = "";
        var scaleFrom = 0;
        var scaleTo = 0;
        var Stop = -99;
        var Dependent = $("#cboDependent").val();
        if ($("#txtScaleTextFrom").length > 0) {
            ScaleTextFrom = $("#txtScaleTextFrom").val();
            scaleFrom = $("#FromScale").val();
        }
        if ($("#txtScaleTextTo").length > 0) {
            ScaleTextTo = $("#txtScaleTextTo").val(); //
            scaleTo = $("#ToScale").val();
        }
        var maxResponse = 0;
        if ($("#txtMaxResponseCount").val() != '')
            maxResponse = $("#txtMaxResponseCount").val();
        var displayRandomResponse = 0;
        if ($("#DisplayRandomResponse").is(':checked'))
            displayRandomResponse = 1;
        var dependentType = $("#ddlDependentType").val();
        var contentType = $("#ddlContentType").val();
        var mediaURL = $("#txtmediaURL").val();
        var data = { DependentID: Dependent, ID: $("#txtID").val(), Code: $("#txtCode").val(), QuestionText: $("#txtContent").val(), Type: $("#ddlQuestionType").val(), ZOrder: $("#txtZOrder").val(), ProjectID: $("#ddlProjectList").val(), ScaleFromText: ScaleTextFrom, ScaleToText: ScaleTextTo, ScaleFrom: scaleFrom, ScaleTo: scaleTo, MaxResponseCount: maxResponse, DisplayRandomResponse: displayRandomResponse, DependentType: dependentType, ContentType: contentType, MediaUrl: mediaURL };
        var pattern = "<ResponseOption Value='{0}'  Caption='Phương án sô {0}' Description='{1}' ZOrder='{0}'/>";
        var ResponseOption = "";
        var ret = "{ResponseOption:[";
        var arrRow = new Array();
        var arrCol = new Array();
        $.each($("input.optAnswers,input.optAnswers2"), function (index, item) {
            var value = $(item).prev().val();
            arrRow.push(value);
            var desc = $(item).val();
            var qID = $(item).attr('qID');
            var qType = $(item).attr('qtype');
            ret += "{";
            var AllowInputText = "0";
            var NonRemember = "0";
            if (typeof qType != 'undefined') {
                // if ($($.string.Format("input[id='AllowInput{0}']:checked", qID)).length>0)
                //    

                if ($(item).prev().prev().children().is(':checked'))
                    AllowInputText = "1";

                if ($(item).next().children().is(':checked'))
                    NonRemember = "1";
            }
            if (data.ID != 0 && qID != undefined)
                ret += $.string.Format("ID:'{0}',", qID);
            ret += $.string.Format("QuestionnaireID:'{0}',", "0");
            ret += $.string.Format("Value:'{0}',", value);
            ret += $.string.Format("AllowInputText:'{0}',", AllowInputText);
            ret += $.string.Format("Type:'{0}',", NonRemember);
            ret += $.string.Format("Caption:'{0}',", desc);
            ret += $.string.Format("ScaleFrom:'{0}',", "0");
            ret += $.string.Format("ScaleFromText:'{0}',", "");
            ret += $.string.Format("ScaleTo:'{0}',", "0");
            ret += $.string.Format("ScaleToText:'{0}',", "");
            ret += $.string.Format("Symbol:'{0}',", "");
            ret += $.string.Format("ZOrder:'{0}',", index);
            ret += $.string.Format("Description:'{0}'", desc);
            ret += "}";
            if (index != $("input.optAnswers").size() - 1) {
                ret += ",";
            }
        });
        ret += "],ColOption:[";
        $.each($("input.optAnswersMatrix"), function (index, item) {
            var value = index + 1;
            var desc = $(item).val();
            var qID = $(item).attr('qID');
            ret += "{";
            if (data.ID != 0 && qID != undefined)
                ret += $.string.Format("ID:'{0}',", qID);
            ret += $.string.Format("QuestionnaireID:'{0}',", "0");
            ret += $.string.Format("Value:'{0}',", value);
            ret += $.string.Format("Caption:'{0}',", desc);
            ret += $.string.Format("ScaleFrom:'{0}',", "0");
            ret += $.string.Format("ScaleFromText:'{0}',", "");
            ret += $.string.Format("ScaleTo:'{0}',", "0");
            ret += $.string.Format("ScaleToText:'{0}',", "");
            ret += $.string.Format("Symbol:'{0}',", "");
            ret += $.string.Format("ZOrder:'{0}',", value);
            ret += $.string.Format("Description:'{0}'", desc);
            ret += "}";
            if (index != $("input.optAnswersMatrix").size() - 1) {
                ret += ",";
            }
        });

        ret += "]}";
        data.Action = type;
        data.ResponseOption = ret;
        var chekOverlap = this.CheckOverlap(arrRow);
        if (chekOverlap != -9999) {
            $.CAlert.Alert({
                Title: "Thông báo",
                Content: $.string.Format("Bạn đang nhập trùng giá trị [{0}] trong danh sách trả lời", chekOverlap)
            }, function () {
                $($.string.Format("#FormEdit input[value='{0}']", chekOverlap))[0].focus();
            });
            return false;
        }

        if (typeof USER_ID != "undefined") {
            data.UserID = USER_ID;
            data.SecrectToken = SECRECT_TOKEN;
        }
        if (type == 'INSERT')
            data.ID = "0";
        $.Ajax({
            url: 'Service/QuestionService.ashx',
            type: 'POST',
            data: data,
            success: function (data, textStatus, jqXHR) {
                if (data) {
                    data = eval("(" + data + ")");
                    if (data.IsSuccessfull == true) {
                        Axis.Admin.Project.Question.List.Grid.Reload();
                    }
                    else {

                        $.CAlert.Alert({
                            Title: "Thông báo",
                            Content: data.Description
                        });
                    }

                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
        return true;
    },
    GenarateListOption: function (pType) {
        // debugger;
        var objThis = this;
        objThis.IndexRow = 1;
        var value = objThis.IndexRow;
        $(".optDivAnswers").remove();
        objThis.ID = 1;
        var type = parseInt(pType);
        $(".QuestionScale").hide();
        $(".QuestionMatrix").hide();
        switch (type) {
            case 0:
                //SA
                $("#FormEdit").append(objThis.GenarateOption(type, objThis.IndexRow, value, ''));
                break;
            case 1:
            case 6:
            case 7:
            case 8:
                //MA  

                $("#FormEdit").append(objThis.GenarateOption(type, objThis.IndexRow, value, ''));
                break;
            case 2:
                //True/Flase
                for (var i = 0; i < 2; i++)
                    $("#FormEdit").append(objThis.GenarateOption(type, 0, i + 1, ''));
                break;
            case 3:
                $("#FormEdit").append(objThis.GenarateOption(type, 0, 0, ''));
                break;
            case 4:
                $(".QuestionScale").show();
                $("#FormEdit").append(objThis.GenarateOption(type, 0, 0, ''));
                break;
            case 5:
            case 9:
            case 10:
                $(".QuestionMatrix").show();
                $("#FormEdit").append(objThis.GenarateOption(type, 0, 0, ''));
                break;
        }
    },
    ShowListOptionByQuestionID: function (objQues, objListRes) {
        var objThis = this;
        var type = parseInt(objQues.QuestionType + '');
        $("#txtID").val(objQues.ID);
        $(".optDivAnswers").remove();
        $(".QuestionScale").hide();
        $(".QuestionMatrix").hide();
        $(".MatrixLine").remove();
        switch (type) {
            case 0:
                //SA
            case 1:
                //MA
            case 2:
            case 6:
            case 7:
            case 8:
                //True/Flase            
                $.each(objListRes, function (index, item) {
                    $("#FormEdit").append(objThis.GenarateOption(type, item.ID, item.Value, item.Caption));
                    $("#txtOption" + item.ID).val(item.Caption).attr('qID', item.ID);
                    objThis.IndexRow = item.ID;
                    if (item.AllowInputText == '1')
                        $("#AllowInput" + item.ID).attr('checked', 'checked');
                    if (item.Type == '1')
                        $("#nonremember" + item.ID).attr('checked', 'checked');

                    objThis.IndexRow = item.Value;
                });
                break;
            case 3:
                $("#FormEdit").append(objThis.GenarateOption(type, 0, item.Value, ''));
                break;
            case 4:
                $(".QuestionScale").show();
                $("#FromScale").val(objQues.ScaleFrom);
                $("#ToScale").val(objQues.ScaleTo);
                $("#FormEdit").append(objThis.GenarateOption(type, 0, item.Value, ''));
                $("#txtScaleTextFrom").val(objQues.ScaleFromText).attr('qID', 0);
                $("#txtScaleTextTo").val(objQues.ScaleToText).attr('qID', 0);
                GenerateScaleQuestion()
                break;
            case 5:
            case 9:
            case 10:
                $(".QuestionMatrix").show();
                var projectID = $("#ddlProjectList").val();
                var thisObj = this;
                var pData = '{' + $.string.Format('"QuestionID":{0},"ProjectID":{1}', objQues.ID, projectID) + '}';
                $.ajax({
                    url: 'Service/ResponseOptionService.asmx/GetQuestionListID',
                    type: 'POST',
                    data: pData,
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (pData, textStatus, jqXHR) {
                        data = eval("(" + pData.d + ")");
                        $("#ColMatrix").val(objListRes.length);
                        $("#RowMatrix").val(data.length - 1);
                        $.each(data, function (i, item) {
                            if (i > 0) {
                                $("#FormEdit").append($.string.Format('<div class="new-row optDivAnswers"> <div class="wrap-control" style="width: 100%;">   <div class="lblAnswersMatrix">Dòng số {0}</div></div><input type="text" Value="{2}"  class="ValueOption" id="ValueOption{3}" /><input type="text" id="txtOption{1}" class="ui-widget-content ui-corner-all optAnswersMatrix" />  </div>', i, item.ID, item.ZOrder));
                                $("#txtOption" + item.ID).val(item.QuestionText).attr('qID', item.ID);
                            }
                        });
                        $("#FormEdit").append("<div class='MatrixLine'></div>");
                        $.each(objListRes, function (i, item) {
                            $("#FormEdit").append($.string.Format('<div class="new-row optDivAnswers"> <div class="wrap-control" style="width: 100%;">   <div class="lblAnswersMatrix">Cột số {0}</div></div><input type="text" Value="{2}"  class="ValueOption" id="ValueOption{3}" /><input type="text" id="txtOptionCol{1}" class="ui-widget-content ui-corner-all optAnswers txtMatrixCol" />  </div>', i + 1, item.ID, item.Value));
                            $("#txtOptionCol" + item.ID).val(item.Caption).attr('qID', item.ID);
                        });


                    },
                    beforeSend: function (jqXHR, settings) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                    },
                    complete: function (XMLHttpRequest, textStatus) {
                    }
                });
                break;
        }
    },
    GetListOption: function (objData) {
        var thisObj = this;
        var pData = '{' + $.string.Format('"QuestionID":{0}', objData.ID) + '}';
        $.ajax({
            url: 'Service/ResponseOptionService.asmx/GeResponseOptionByQuestionID',
            type: 'POST',
            data: pData,
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (pData, textStatus, jqXHR) {
                data = eval("(" + pData.d + ")");
                if (data) {
                    thisObj.ShowListOptionByQuestionID(objData, data);

                }
            },
            beforeSend: function (jqXHR, settings) {
            },
            error: function (jqXHR, textStatus, errorThrown) {
            },
            complete: function (XMLHttpRequest, textStatus) {
            }
        });
    },
    GenarateOption: function (pType, qID, value, text) {
        var objThis = this;
        var index = objThis.ID++;
        var pattern = "";
        switch (pType) {
            case 0:
                //SA 
            case 2:
                pattern = '<div class="new-row optDivAnswers"> <div class="wrap-control"> <input  type="radio" name="sentence" value="{1}" id="AllowInput{0}"/></div><input type="text" Value="{3}"  class="ValueOption" id="ValueOption{3}" /><input type="text" qID="0" qValue="{3}" id="txtOption{0}" class="ui-widget-content ui-corner-all optAnswers" qType="{2}"  />  </div>';
                break;
            case 1:
            case 6:
            case 7:
                //MA
                pattern = '<div class="new-row optDivAnswers"> <div class="wrap-control"> <input qID="{0}" qValue="{3}"  type="checkbox" name="sentence" value="{1}" id="AllowInput{0}"/></div><input type="text" Value="{3}"  class="ValueOption" id="ValueOption{3}" /><input type="text" qID="0" qValue="{3}" id="txtOption{0}" class="ui-widget-content ui-corner-all optAnswers2" qType="1"/> <div class="wrap-control nonremember" title="Không nhớ không biết"> <input qID="nonremember{0}" qValue="{3}"  type="checkbox" name="sentence" value="{1}" id="nonremember{0}"/></div>  </div>';
                break;
            case 8:
                //MA
                pattern = '<div class="new-row optDivAnswers"> <div class="wrap-control"> <input qID="{0}" qValue="{3}"  type="checkbox" name="sentence" value="{1}" id="AllowInput{0}"/></div><input type="text" Value="{3}"  class="ValueOption" id="ValueOption{3}" /><input type="text" qID="0" qValue="{3}" id="txtOption{0}" class="ui-widget-content ui-corner-all optAnswers" qType="8"/>  </div>';
                break;
            case 3:
                //text
                pattern = '<div class="new-row optDivAnswers"> <div class="wrap-control"> <div class="QuestionOpen">&nbsp;</div></div><input type="text" Value="{0}"  class="ValueOption" id="ValueOption{3}" /><input type="text" qID="{0}" qValue="{3}" value="{1}" id="txtOption{0}" class="ui-widget-content ui-corner-all optAnswers"/>  </div>';
                break;
            case 4:
                //Scale
                pattern = '<div class="new-row optDivAnswers"> <div class="wrap-control">   <div class="lblScaleFrom" id="lblScaleFrom">{0}</div></div><input type="text" id="txtScaleTextFrom" class="ui-widget-content ui-corner-all optAnswers" />  </div><div class="new-row optDivAnswers"> <div class="wrap-control"> <div class="lblScaleFrom" id="lblScaleTo">{1}</div> </div><input type="text" id="txtScaleTextTo" class="ui-widget-content ui-corner-all optAnswers"  />  </div>';
                pattern = $.string.Format(pattern, $("#FromScale").val(), $("#ToScale").val(), pType);
                break;
            case 5:
            case 9:
            case 10:
                var colText = "";
                var rowText = "";
                var numCol = $("#ColMatrix").val();
                var numRow = $("#RowMatrix").val();
                for (var i = 0; i < numRow; i++)
                    rowText += $.string.Format('<div class="new-row optDivAnswers"> <div class="wrap-control" style="width:100%">   <div class="lblAnswersMatrix">Dòng số {0}</div></div><input type="text" Value="{0}"  class="ValueOption" id="ValueOption{3}" /><input type="text" id="txtOption{0}" class="ui-widget-content ui-corner-all optAnswersMatrix"  />  </div>', i + 1);
                for (var i = 0; i < numCol; i++)
                    colText += $.string.Format('<div class="new-row optDivAnswers"> <div class="wrap-control"  style="width:100%">   <div class="lblAnswersMatrix">Cột số {0}</div></div><input type="text" Value="{0}"  class="ValueOption" id="ValueOption{3}" /><input type="text" id="txtOptionCol{0}" class="ui-widget-content ui-corner-all optAnswers txtMatrixCol" />  </div>', i + 1);
                pattern += rowText + "<div class='MatrixLine'></div>" + colText;
                break;
        }
        return $.string.Format(pattern, qID, text, pType, value);
    }
}

$(function () {
    var objThis = Axis.Admin.OptionAnswer;
    $(".optAnswers,.optAnswers2").live('keydown', 'Return', function (evt) {
        var type = parseInt($("#ddlQuestionType").val() + '');
        if (type == 0 || type == 1 || type == 6 || type == 8 || type == 7) {
            objThis.IndexRow++;
            var value = objThis.IndexRow;
            $("#FormEdit").append();
            $(objThis.GenarateOption(type, 0, value, '')).insertAfter($(this).parent());

            $($.string.Format("#ValueOption{0}", value)).focus();

            // $(".optAnswers:last").focus();
        }
        return false;
    }).live('keydown', 'DEL', function (evt) {
        var type = parseInt($("#ddlQuestionType").val() + '');
        if (type == 0 || type == 1) {
            $(this).parent().remove();
        }
        return false;
    });


    $("#btnSelectImg").click(function () {
        var finder = new CKFinder();
        finder.resourceType = 'Images';
        finder.startupPath = "Images:/Project/";
        finder.selectActionFunction = function (fileUrl) {
            $('#txtmediaURL').val(fileUrl);
        };
        finder.popup();
    });


});
function GenarateListOption(obj) {
    var objThis = Axis.Admin.OptionAnswer;
    var pType = $(obj).val();
    objThis.GenarateListOption(pType);
}
function GenerateScaleQuestion() {
    var objThis = Axis.Admin.OptionAnswer;
    //objThis.GenarateListOption();
    $("#lblScaleFrom").html($("#FromScale").val());
    $("#lblScaleTo").html($("#ToScale").val());
}
function GenerateMatrixQuestion() {
    var objThis = Axis.Admin.OptionAnswer;
    $(".MatrixLine").remove();
    objThis.GenarateListOption("5");
};